﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace QD.Tools
{
    public static class StringHelper
    {
        /// <summary>
        /// 取字符的真实长度（一个汉字的长度为2）
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static int GetTrueLength(this string str)
        {
            byte[] _b = System.Text.Encoding.Default.GetBytes(str);
            return _b.Length;
        }

        /// <summary>
        /// 判断字符串是否包含指定的关键字
        /// </summary>
        /// <param name="str"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static bool IsContains(this string str, params string[] keys)
        {
            if (str.Length == 0)
            {
                return false;
            }
            else if (keys.Length == 0)
            {
                return false;
            }
            else
            {
                bool isContains = false;
                foreach (string key in keys)
                {
                    isContains = str.ToLower().Contains(key);
                    if (isContains)
                    {
                        break;
                    }
                }

                return isContains;
            }
        }

        /// <summary>
        /// 返回MD5加密后的字符(注：该加密方法必须保持与QDORM.ToolsHelper.ToMD5Encryption加密方法一致，因两处都用于创建用户密码）
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string ToMD5Encryption(this string str)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] oriByte = System.Text.Encoding.Default.GetBytes(str);
            byte[] md5Result = md5.ComputeHash(oriByte);
            string enStr = BitConverter.ToString(md5Result).Replace("-", "");
            return enStr;
        }

        /// <summary>
        /// 是否为字符串类型
        /// </summary>
        /// <returns></returns>
        public static bool IsStringColumnType(this string columnType)
        {
            if (columnType.ToLower().IsContains("char", "datetime"))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 是否为nvarchar或者nchar类型
        /// </summary>
        /// <returns></returns>
        public static bool IsNcharColumnType(this string columnType)
        {
            if (columnType.ToLower().IsContains("nchar", "nvarchar"))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}
